package carassius.DAL;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author siebz0r
 */
public class WaterMeasurementListTable
		extends Table<WaterMeasurementListRow, SimpleEntry<Integer, String>>
{
	private final String SQL_ADD = "INSERT INTO water_measurement_list VALUES ( ? , ? , ? )",
			SQL_DELETE = "DELETE FROM water_measurement_list WHERE measurement_id = ? AND condition = ?",
			SQL_DELETE_BY_MEASUREMENT_ID = "DELETE FROM water_measurement_list WHERE measurement_id = ?",
			SQL_DELETE_BY_CONDITION_NAME = "DELETE FROM water_measurement_list WHERE condition = ?",
			SQL_GET_ALL = "SELECT * FROM water_measurement_list",
			SQL_GET_BY_MEASUREMENT_ID = "SELECT * FROM water_measurement_list WHERE measurement_id = ?",
			SQL_GET_BY_CONDITION_NAME = "SELECT * FROM water_measurement_list WHERE condition = ?",
			SQL_GET_BY_MEASUREMENT_ID_AND_CONDITION_NAME = "SELECT * FROM water_measurement_list WHERE measurement_id = ? and condition = ?";
	private boolean _allCached;

	//<editor-fold defaultstate="collapsed" desc="Public Methods">
	//<editor-fold defaultstate="collapsed" desc="SQL add">
	public WaterMeasurementListRow add(WaterMeasurementRow waterMeasurementRow,
									   WaterConditionRow waterConditionRow,
									   Double value) throws SQLException
	{
		if(waterMeasurementRow != null
				&& waterConditionRow != null)
		{
			return add(waterMeasurementRow.getId(), waterConditionRow.getName(), value);
		}
		return null;
	}

	public WaterMeasurementListRow add(Integer waterMeasurementId,
									   String waterCondition, Double value) throws SQLException
	{
		SimpleEntry<Integer, String> keys = add(new Object[]
				{
					waterMeasurementId, waterCondition, value
				});
		if (keys != null)
		{
			return getByPrimaryKey(keys);
		}
		return null;
	}

	@Override
	public SimpleEntry<Integer, String> add(Object[] args) throws SQLException
	{
		SimpleEntry<Integer, String> out = null;
		if (args != null
				&& args.length >= 3
				&& ((args[0] instanceof Integer && (Integer) args[0] >= 0)
				|| (args[0] instanceof WaterMeasurementRow && ((WaterMeasurementRow) args[0]).getId() >= 0))
				&& ((args[1] instanceof String && !((String) args[1]).isEmpty())
				|| (args[1] instanceof WaterConditionRow && (((WaterConditionRow) args[1]).getName() != null && !((WaterConditionRow) args[1]).getName().isEmpty())))
				&& args[2] instanceof Double && (Double) args[2] > 0)
		{
			out = new SimpleEntry<Integer, String>((args[0] instanceof Integer) ? (Integer) args[0] : ((WaterMeasurementRow) args[0]).getId(),
					(args[1] instanceof String) ? (String) args[1] : ((WaterConditionRow) args[1]).getName());
			PreparedStatement st = Database.prepareStatement(SQL_ADD);
			st.setInt(1, out.getKey());
			st.setString(2, out.getValue());
			st.setObject(3, args[2], Types.DOUBLE);

			try
			{
				synchronized (getRows())
				{
					if (st.executeUpdate() == 1)
					{
						_allCached = false;
						getByPrimaryKey(out);
						_allCached = true;
					}
					else
					{
						out = null;
					}
				}
			}
			catch (SQLException ex)
			{
				throw ex;
			}
			finally
			{
				st.close();
			}
		}
		return out;
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="SQL delete">
	@Override
	public boolean delete(SimpleEntry<Integer, String> keys) throws SQLException
	{
		boolean result = false;
		if (keys != null
				&& keys.getKey() != null
				&& keys.getKey() >= 0
				&& keys.getValue() != null
				&& !keys.getValue().isEmpty())
		{
			PreparedStatement st = Database.prepareStatement(SQL_DELETE);
			st.setInt(1, keys.getKey());
			st.setString(2, keys.getValue());

			try
			{
				synchronized (getRows())
				{
					if (result = (st.executeUpdate() == 1))
					{
						getRows().remove(keys);
					}
				}
			}
			catch (SQLException ex)
			{
				throw ex;
			}
			finally
			{
				st.close();
			}
		}
		return result;
	}

	public boolean deleteByMeasurementID(int id) throws SQLException
	{
		boolean result = false;
		if (id >= 0)
		{
			synchronized (getRows())
			{
				PreparedStatement st = Database.prepareStatement(SQL_DELETE_BY_MEASUREMENT_ID);
				st.setInt(1, id);

				try
				{
					ArrayList<WaterMeasurementListRow> removeQueue = getByMeasurementID(id);
					if (result = (st.executeUpdate() == removeQueue.size()))
					{
						for (WaterMeasurementListRow waterMeasurementListRow : removeQueue)
						{
							getRows().remove(waterMeasurementListRow.getPrimaryKeys());
						}
					}
				}
				catch (SQLException ex)
				{
					throw ex;
				}
				finally
				{
					st.close();
				}
			}
		}
		return result;
	}

	public boolean deleteByConditionName(String name) throws SQLException
	{
		boolean result = false;
		if (name != null && !name.isEmpty())
		{

			PreparedStatement st = Database.prepareStatement(SQL_DELETE_BY_CONDITION_NAME);
			st.setString(1, name.trim());

			synchronized (getRows())
			{
				ArrayList<WaterMeasurementListRow> removeQueue = getByConditionName(name);
				try
				{
					if (result = (st.executeUpdate() == removeQueue.size()))
					{
						for (WaterMeasurementListRow waterMeasurementListRow : removeQueue)
						{
							getRows().remove(waterMeasurementListRow.getPrimaryKeys());
						}
					}
				}
				catch (SQLException ex)
				{
					throw ex;
				}
				finally
				{
					st.close();
				}
			}
		}
		return result;
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Sql get">
	@Override
	public Collection<WaterMeasurementListRow> getAll() throws SQLException
	{
		synchronized (getRows())
		{
			if (!_allCached)
			{
				PreparedStatement st = Database.prepareStatement(SQL_GET_ALL);

				try
				{
					ResultSet query = st.executeQuery();

					while (query.next())
					{
						put(new WaterMeasurementListRow(query));
					}
					_allCached = true;
				}
				catch (SQLException ex)
				{
					throw ex;
				}
				finally
				{
					st.close();
				}
			}
		}
		return getRows().values();
	}

	public ArrayList<WaterMeasurementListRow> getByMeasurementID(int id) throws SQLException
	{
		ArrayList<WaterMeasurementListRow> out = null;
		if (id >= 0)
		{
			out = new ArrayList<WaterMeasurementListRow>();
			if (_allCached)
			{
				for (WaterMeasurementListRow waterMeasurementListRow : getRows().values())
				{
					if (waterMeasurementListRow.getWaterMeasurementRow().getId() == id)
					{
						out.add(waterMeasurementListRow);
					}
				}
			}
			else
			{
				PreparedStatement st = Database.prepareStatement(SQL_GET_BY_MEASUREMENT_ID);
				st.setInt(1, id);

				try
				{
					synchronized (getRows())
					{
						ResultSet query = st.executeQuery();
						while (query.next())
						{
							WaterMeasurementListRow waterMeasurementListRow = new WaterMeasurementListRow(query);
							out.add(waterMeasurementListRow);
							put(waterMeasurementListRow);
						}
					}
				}
				catch (SQLException ex)
				{
					throw ex;
				}
				finally
				{
					st.close();
				}
			}
		}
		return out;
	}

	public ArrayList<WaterMeasurementListRow> getByConditionName(String name) throws SQLException
	{
		ArrayList<WaterMeasurementListRow> out = null;
		if (name != null && !name.trim().isEmpty())
		{
			synchronized (getRows())
			{
				if (_allCached)
				{
					for (WaterMeasurementListRow waterMeasurementListRow : getRows().values())
					{
						if (waterMeasurementListRow.getWaterConditionRow().getName().equals(name))
						{
							out.add(waterMeasurementListRow);
						}
					}
				}
				else
				{
					PreparedStatement st = Database.prepareStatement(SQL_GET_BY_CONDITION_NAME);
					st.setString(1, name);

					try
					{
						ResultSet query = st.executeQuery();
						getRows().clear();

						while (query.next())
						{
							WaterMeasurementListRow waterMeasurementListRow = new WaterMeasurementListRow(query);
							out.add(waterMeasurementListRow);
							put(waterMeasurementListRow);
						}
					}
					catch (SQLException ex)
					{
						throw ex;
					}
					finally
					{
						st.close();
					}
				}
			}
		}
		return out;
	}

	@Override
	public WaterMeasurementListRow getByPrimaryKey(
			SimpleEntry<Integer, String> keys) throws SQLException
	{
		WaterMeasurementListRow row = null;
		if (keys != null
				&& keys.getKey() != null
				&& keys.getKey() >= 0
				&& keys.getValue() != null
				&& !keys.getValue().isEmpty())
		{
			row = getRows().get(keys);
			if (row != null || _allCached)
			{
				return row;
			}

			PreparedStatement st = Database.prepareStatement(SQL_GET_BY_MEASUREMENT_ID_AND_CONDITION_NAME);
			st.setInt(1, keys.getKey());
			st.setString(2, keys.getValue());

			try
			{
				synchronized (getRows())
				{
					ResultSet query = st.executeQuery();

					if (query.next())
					{
						row = new WaterMeasurementListRow(query);
						put(row);
					}
				}
			}
			catch (SQLException ex)
			{
				throw ex;
			}
			finally
			{
				st.close();
			}
		}
		return row;
	}
	//</editor-fold>
	//</editor-fold>
}
